<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" />

    <style class="cp-pen-styles">
        * {
            margin: 0;
            padding: 0;
        }

        html,
        body {
            height: 100%;
            overflow: hidden;
        }
    </style>
</head>

<body>
    <!-- 加入，模型屏幕位置，取消转角，去除不必要的初始化属性，闪点效果 -->

    <!-- <button class="dianji1"></button> -->
    
    <button class="dianji2" model="0">切换前</button>
    <button class="dianji3" model="1">切换后</button>


    <script src="https://cdn.bootcss.com/three.js/90/three.min.js"></script>
    <!-- <script src="/page/lib/OrbitControls.js"></script> -->
    <script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
    <script src="https://cdn.bootcss.com/tween.js/17.2.0/Tween.js"></script>
    <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>

    <script>
        function init() {
            var ismobile = !1;

            /iPhone|iPad|iPod|Android/i.test(navigator.userAgent) ? ismobile = !0 : "";

            // 获取浏览器窗口的宽高，后续会用
            var width = window.innerWidth
            var height = window.innerHeight

            // 创建一个场景
            var scene = new THREE.Scene()

            // 创建一个具有透视效果的摄像机
            var camera = new THREE.PerspectiveCamera(75, width / height, 1, 5e4)

            // 设置摄像机位置，并将其朝向场景中心
            // camera.position.x = 10;
            // camera.position.y = 100;
            // camera.position.z = 800;
            // camera.lookAt(scene.position)
            camera.position.set(0, 0, 1e3),
            camera.lookAt(new THREE.Vector3(0, 0, 0))

            // 创建一个 WebGL 渲染器，Three.js 还提供 <canvas>, <svg>, CSS3D 渲染器。
            var renderer = new THREE.WebGLRenderer({
                antialias: true
            })

            // 设置渲染器的清除颜色（即绘制下一帧前填充的颜色）和输出的 canvas 的尺寸
            renderer.setClearColor(0x000000)
            renderer.setSize(width, height)

            // 将渲染器的输出（此处是 canvas 元素）插入到 body
            document.body.appendChild(renderer.domElement)

            // 初始化摄像机插件（用于拖拽旋转摄像机，产生交互效果）
            var orbitControls = new THREE.OrbitControls(camera)

            orbitControls.enabled = 1;
            orbitControls.autoRotate = !1;
            orbitControls.autoRotateSpeed = 10; // 30 seconds per round when fps is 60



            //在网页上显示坐标系，其中坐标系的长度为6
            var axisHelper = new THREE.AxesHelper(200);
            // scene.add(axisHelper);


            // 粒子的材质
            var spriteMaterial = new THREE.SpriteMaterial({
                "color": new THREE.Color(0xffffff)
            })
            var spriteMaterial2 = new THREE.SpriteMaterial({
                map: program()
            })

            //画点 贴图
            function program() {
                var canvas = document.createElement('canvas');
                canvas.width = 64;
                canvas.height = 64;

                var context = canvas.getContext('2d');
                var gradient = context.createRadialGradient(canvas.width / 2, canvas.height / 2, 0, canvas.width / 2,
                    canvas.height / 2, canvas.width / 2);
// new THREE.Color("hsl(" + (160 + 0 * Math.random()) + ", 100%, 100%)")
                gradient.addColorStop(0, 'rgba(250,250,250,1)');
                gradient.addColorStop(.9, 'rgba(250,250,250,.9)');
                gradient.addColorStop(1, 'rgba(1,1,1,1)');

                context.fillStyle = gradient;
                context.fillRect(0, 0, canvas.width, canvas.height);

                var texture = new THREE.Texture(canvas);
                texture.needsUpdate = true;
                return texture;
            };

            // 循环创建多个 THREE.Sprite 对象，该对象始终面向摄像机
            // l粒子数
            var tween;
            var loader = new THREE.JSONLoader();
            var Djson = [
                "./mx/cpgame3.json",
                "./mx/cpac5.json",
                "./mx/cpbook2.json",
                "./mx/cpmovie4.json",
                "./mx/cpkv3.json",
                "./mx/qr.json"
            ];
            var numMX = 5;//模型总数
            
            var theSprite = [];//使用的粒子 7524

            var theArr = dianXinXi();//初始化使用的 粒子

            var loadMXRun; //执行 动画的函数
            var n = [700, 700, 1e3, 1200, 1500, 500],
                r = [[72, 30, 60], [0, -30, 0], [0, 0, 0], [90, 180, 0], [10, 0, 0], [0, 0, 0]],
                o = [[- 400, 100, 0], [400, 0, 0], [- 500, 150, 0], [0, 0, 0], [0, -500, 0], [0, 0, 0]];
            function loadMX(shu) {
                loader.load(Djson[shu], function (geometry, materials) {

                    // console.log("粒子2", geometry.vertices)
                    // console.log("粒子2", geometry.scale)
                    geometry.center(),
                    geometry.normalize(),
                    geometry.rotateX(3.14 * r[shu][0] / 180),
                    geometry.rotateY(3.14 * r[shu][1] / 180),
                    geometry.rotateZ(3.14 * r[shu][2] / 180),
                    geometry.scale(n[shu], n[shu], n[shu]),
                    geometry.translate(o[shu][0], o[shu][1], o[shu][2]);
                    // 当前的模型  粒子
                    var theMXSprite = geometry.vertices;

                    console.log(theMXSprite.length)




                    theSprite.forEach(function (child, index) {
                        // console.log(index,child)

                        var thisSprite = theMXSprite[index%theMXSprite.length]
                        var Tpoint = child;
                        var Epoint = {
                            "index":index,
                            "x": thisSprite.x,
                            "y": thisSprite.y,
                            "z": thisSprite.z
                        };
                        // theSprite[index].x = thisSprite.x
                        // theSprite[index].y = thisSprite.y
                        // theSprite[index].z = thisSprite.z

                        tween = new TWEEN.Tween(Tpoint)
                            .to(Epoint, 2000)
                            .delay(Math.random() * 500)
                            .easing(TWEEN.Easing.Quartic.Out)
                            .onUpdate(function (pp) {
                                // console.log(pp)
                                pp.sprite.position.set(pp.x, pp.y, pp.z)
                                // pp.point.position.addScaledVector(pp,10000)
                                // pp.point.material.opacity = Math.random().toFixed(2);
                                // pp.point.position.set(pp.x * 8, pp.y * 8, pp.z * 8)
                            }).start();
                            // console.count()
                                              

                    })



                    // 异步执行
                    console.log("异步执行")

                    animate()

                });
            }




            var mytime;

            function animate(time) {
                // 渲染，即摄像机拍下此刻的场景
                // renderer.render(scene, camera)
                // requestAnimationFrame(animate)
                orbitControls.update();

                renderer.render(scene, camera)
                // var id = requestAnimationFrame(animate);
                // mytime = setTimeout(animate, 30);
                var result = TWEEN.update(time);

                // console.log(result)

                // if(!result) changeColor();
                // if (!result) cancelAnimationFrame(id);


                if(result){
                    clearTimeout(mytime)
                    mytime = setTimeout(animate, 30);
                }else{

                    clearTimeout(mytime)

                    mytime = setTimeout(animate, 100);
                    
                    // changeColor();
                }
            }

            // 禁用鼠标         
            orbitControls.enabled = !1;
            // $(".dianji1").click(function () {
            //     if ($(this).html() == "暂停") {
            //         orbitControls.enabled = !1;
            //         $(this).html("开始")
            //     } else {
            //         orbitControls.enabled = 1;
            //         $(this).html("暂停")

            //     }
            // })

            $(".dianji2").click(function () {

                // loadMXRun2 = loadMX;
                loadMXRun = loadMX;
                loadMXRun((++numMX)%6);
                
            })
             $(".dianji3").click(function () {
                loadMXRun = loadMX;
                numMX < 1 ? numMX = 5 : --numMX
                loadMXRun(numMX % 6);
             })





            function dianXinXi() {
                console.log("dianXinXi")

                var e = new THREE.TextureLoader;
                e.crossOrigin = "",
                e.load("http://game.gtimg.cn/images/up/act/a20170301pre/images/three/gradient.png",function (e) {
                    var spriteMaterial3 = new THREE.SpriteMaterial({
                        // "opacity":Math.random().toFixed(2)*0.5,
                        // "color": new THREE.Color("hsl(" + (160 + 0 * Math.random()) + ", 100%, 100%)")
                        // "color": new THREE.Color('#ffffff')
                    })
                    console.log(spriteMaterial3)
                    spriteMaterial3.map = e,
                    spriteMaterial3.needsUpdate = !0
                    
                    var spriteGroup = new  THREE.Object3D()

                    for (var index = 0; index < 7524; index++) {
                        
                        // console.log("getColor()", getColor())

                        var sprite = new THREE.Sprite(spriteMaterial3)
                        // sprite.scale.addScalar(ismobile ? .8 : .5)
                        sprite.scale.addScalar(1)

                        if(index<5) console.log(sprite)
                        
                        // console.log(sprite.material)

                        theSprite[index] = {
                            sprite: sprite,
                            x: 0,
                            y: 0,
                            z: 0

                        };
                        sprite.scale.addScalar(3)
                        
                        spriteGroup.add(sprite)

                    }

                    console.log(spriteGroup)
                    scene.add(spriteGroup)
                    
                    
                    

                    loadMXRun = loadMX;
                    loadMXRun(numMX);
                })
            }

            function changeColor() {
                
                for(var i in theSprite ){
                    if(Math.random()>.95){
                        var tcolor = theSprite[i].sprite.material.opacity;
                        tcolor = tcolor>0.8?0.4: tcolor+=0.1;
                        theSprite[i].sprite.material.opacity = tcolor
                    }
                    // console.log(theSprite[i].sprite.material.opacity)
                }
            }

            // changeColor() ;
        }
        init();
    </script>
</body>

</html>